package com.service.config.utils;

import com.service.config.constant.Constant;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Locale;

/**
 * @author: hjl
 * @date: 2022/07/22 16:50
 * @description:
 */
public class AesEncryptHandler extends BaseTypeHandler {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {
        String plainText = String.valueOf(parameter);
        if(StringUtils.isEmpty(plainText)){
            ps.setString(i,plainText);
        }else {
            try {
                ps.setString(i,String.format(Locale.ROOT,"%s%s%s", Constant.CIPHER_PREFIX,Constant.COLON,DesUtil.encrypt(plainText)));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public Object getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String columnValue = rs.getString(columnName);
        return getAble(columnValue);
    }

    @Override
    public Object getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String columnValue = rs.getString(columnIndex);
        return getAble(columnValue);
    }

    @Override
    public Object getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String columnValue = cs.getString(columnIndex);
       return getAble(columnValue);
    }
    private String  getAble (String columnValue ) {
        try {
            if (StringUtils.isNotEmpty(columnValue) && columnValue.contains(Constant.CIPHER_PREFIX)) {
                String[] array = columnValue.split(Constant.COLON);
                return array.length > 1 ? DesUtil.decrypt(array[1]) : columnValue;
            }
            return columnValue;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return columnValue;
    }
}
